<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生日匹配展示</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f4f4f9;
            display: flex;
            margin: 0;
            line-height: 1.8;
        }

        h1 {
            color: #333;
            margin: 20px 0;
            font-size: 28px;
            padding: 10px 0;
            width: 100%;
            text-align: center;
            background-color: #f4f4f9;
            position: fixed;
            top: 0;
            z-index: 1;
        }

        #content {
            margin-top: 80px;
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        #date-selector {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            gap: 10px;
        }

        #date-selector label {
            font-size: 20px;
        }

        #date-selector select {
            padding: 6px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 18px;
        }

        #date-selector button {
            padding: 6px 10px;
            background-color: #007BFF;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 18px;
        }

        #date-list {
            margin-bottom: 20px;
        }

        #student-list {
            position: fixed;
            top: 80px;
            right: 0;
            width: 30%;
            background-color: #f9f9f9;
            border-left: 1px solid #ccc;
            padding: 10px;
            overflow-y: auto;
            max-height: calc(100vh - 80px);
        }

        .student {
            display: inline-block;
            margin: 2px;
            padding: 4px 8px;
            border: 1px solid #ccc;
            cursor: move;
            font-size: 14px;
        }

        .date-row {
            margin-bottom: 10px;
            min-height: 30px;
            width: 100%;
            text-align: center;
        }

        .date {
            display: inline-block;
            margin-right: 10px;
            color: #FF6600;
            font-size: 22px;
            font-weight: 600;
        }

        .students-on-date span {
            margin: 5px 8px;
            display: inline-block;
            border: 1px solid #ccc;
            padding: 3px 5px;
        }

        .student-container {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 5px;
        }

        .student-placeholder {
            visibility: hidden;
            border: 1px dashed #ccc;
            min-height: 20px;
        }
    </style>
</head>

<body>
    <h1>生日匹配展示</h1>
    <div id="content">
        <!-- 日期选择器 -->
        <div id="date-selector">
            <label for="month">月份</label>
            <select id="month">
                <option value="1">1月</option>
                <option value="2">2月</option>
                <option value="3">3月</option>
                <option value="4">4月</option>
                <option value="5">5月</option>
                <option value="6">6月</option>
                <option value="7">7月</option>
                <option value="8">8月</option>
                <option value="9">9月</option>
                <option value="10">10月</option>
                <option value="11">11月</option>
                <option value="12">12月</option>
            </select>
            <label for="day">日期</label>
            <select id="day">
            </select>
            <button id="same-day-button">同一天</button>
        </div>

        <!-- 日期列表 -->
        <div id="date-list"></div>
    </div>

    <!-- 学生列表 -->
    <div id="student-list">
        <div class="student-container" id="student-holder"></div>
    </div>

    <script>
        const daySelect = document.getElementById('day');
        const monthSelect = document.getElementById('month');

        function updateDayOptions() {
            const month = parseInt(monthSelect.value);
            const daysInMonth = new Date(new Date().getFullYear(), month, 0).getDate();
            daySelect.innerHTML = '';
            for (let i = 1; i <= daysInMonth; i++) {
                const option = document.createElement('option');
                option.value = i;
                option.textContent = i + '日';
                daySelect.appendChild(option);
            }
        }

        monthSelect.addEventListener('change', updateDayOptions);
        updateDayOptions();

        const sameDayButton = document.getElementById('same-day-button');
        const dateList = document.getElementById('date-list');
        const selectedDates = new Set();
        sameDayButton.addEventListener('click', () => {
            const month = document.getElementById('month').value;
            const day = document.getElementById('day').value;
            const fullDate = `${month}月${day}日`;
            if (!selectedDates.has(fullDate)) {
                const dateRow = document.createElement('div');
                dateRow.classList.add('date-row');
                const dateSpan = document.createElement('span');
                dateSpan.classList.add('date');
                dateSpan.textContent = fullDate;
                const studentsOnDateSpan = document.createElement('span');
                studentsOnDateSpan.classList.add('students-on-date');
                dateRow.appendChild(dateSpan);
                dateRow.appendChild(studentsOnDateSpan);
                dateList.appendChild(dateRow);
                selectedDates.add(fullDate);
                setupDragAndDrop();
            }
        });

        const excelImport = document.getElementById('excel-import');
        const studentData = {};
        const studentHolder = document.getElementById('student-holder');

        // 从数据库获取学生数据
        async function fetchStudentsFromDB() {
            try {
                const response = await fetch('/api/students');
                if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);
                const students = await response.json();
                console.log('获取到的学生数据:', students);
                
                studentHolder.innerHTML = '';
                students.forEach((name, index) => {
                    const studentDiv = document.createElement('div');
                    studentDiv.classList.add('student');
                    studentDiv.draggable = true;
                    studentDiv.textContent = name; // 直接使用数组中的字符串
                    studentDiv.dataset.id = index; // 使用索引作为临时ID
                    studentHolder.appendChild(studentDiv);
                });
                
                setupDragAndDrop();
            } catch (error) {
                console.error('获取学生数据失败:', error);
                studentHolder.innerHTML = `<div style="color:red">加载失败: ${error.message}</div>`;
            }
        }

        // 页面加载时获取学生数据
        document.addEventListener('DOMContentLoaded', fetchStudentsFromDB);

        function setupDragAndDrop() {
            const students = document.querySelectorAll('.student');
            let draggedStudent;

            students.forEach((student) => {
                student.addEventListener('dragstart', (e) => {
                    draggedStudent = student;
                    e.dataTransfer.effectAllowed = 'move';
                    e.dataTransfer.setData('text/plain', '');
                });

                student.addEventListener('dragend', () => {
                    if (draggedStudent) {
                        draggedStudent = null;
                    }
                });
            });

            const dateRows = document.querySelectorAll('.date-row');
            dateRows.forEach((dateRow) => {
                dateRow.addEventListener('dragover', (e) => {
                    e.preventDefault();
                    e.dataTransfer.dropEffect = 'move';
                });

                dateRow.addEventListener('drop', (e) => {
                    e.preventDefault();
                    const studentsOnDate = dateRow.querySelector('.students-on-date');
                    const existingSpans = studentsOnDate.querySelectorAll('span');
                    const isAdded = Array.from(existingSpans).some(span => span.textContent === draggedStudent.textContent);
                    if (!isAdded && draggedStudent) {
                        const newStudent = document.createElement('span');
                        newStudent.textContent = draggedStudent.textContent;
                        studentsOnDate.appendChild(newStudent);

                        const placeholder = document.createElement('div');
                        placeholder.classList.add('student-placeholder');
                        draggedStudent.parentNode.insertBefore(placeholder, draggedStudent);
                        draggedStudent.remove();
                    }
                });
            });
        }
    </script>
</body>
</html>